package com.yq.utils;

import com.google.gson.Gson;
import com.yq.model.Result;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class HttpUtils {
    private HttpUtils(){};
    /**
     * 获取请求的参数
     *
     * @param request
     * @return
     * @throws IOException
     */

    public static String getRequestInfo(HttpServletRequest request) throws IOException {
        //获取数据
        ServletInputStream inputStream = request.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int leng;
        while ((leng = inputStream.read(bytes))!=-1){
            byteArrayOutputStream.write(bytes,0,leng);
        }
        String requestInfo = byteArrayOutputStream.toString("utf-8");
        byteArrayOutputStream.close();
        return requestInfo;
    }


    public static void responseInfo(int code, HttpServletResponse response) throws IOException {
        Gson gson = new Gson();
        Result result = null;
        if (code == 200) {
            result = Result.ok();
        } else if (code == 404) {
            result = Result.error("操作不成功");
        }
        response.getWriter().println(gson.toJson(result));
    }
}
